const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const {writeFileSync} = require('fs');
const {resolve} = require('path');

const PORT = 8080;
const app = express();
app.use(bodyParser.json());

app.use('/{*splat}',(req, res, next) => {
  console.log(req.url);
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type,x-ext');
  res.header('Access-Control-Allow-Methods', 'GET,POST');
  if (req.method === "OPTIONS") return res.sendStatus(200);
  next();
})
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    const ext = file.originalname.split('.')[1];
    cb(null, Date.now() + '.' + ext);
  }
})

const upload = multer({
  storage,
})


// multipart/form-data
app.post('/file',upload.single('file'), (req, res) => {
  if(req.file){
    res.send({
      code:0,
      msg:'ok'
    })
  }else{
    res.send({
      code:1,
      msg:'error'
    })
  }
});
//base64上传
app.post('/base64',(req,res)=>{
  const {file,ext} = req.body;
  const binaryData = Buffer.from(file,'base64');
  writeFileSync(resolve(__dirname,`./uploads/${Date.now()}.${ext}`),binaryData,'binary');
  res.send({
    code:0,
    msg:"ok",
  })
});

app.post('/binary',(req,res)=>{
  const ext = req.headers['x-ext'];
  const buffers =  [];

  req.on('data',chunk=>{
    buffers.push(chunk);
  }).on('end',()=>{
    const binaryData = Buffer.concat(buffers);
    writeFileSync(resolve(__dirname,`./uploads/${Date.now()}.${ext}`),binaryData,'binary');
    res.send({
      code:0,
      msg:'ok',
    })
  })

})

app.listen(PORT, () => {
  console.log('listen at http://localhost:'+PORT);
})
